package com.cloud.controller;

import com.cloud.model.system.SysResource;
import com.cloud.service.SysResourceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.map.HashedMap;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mj on 2017/3/30.
 */
@RestController
public class SysResourceController {
    @Autowired
    private SysResourceService sysResourceService;
    /**
     * 资源菜单
     * @return
     */
    @GetMapping(value = "resources")
    public String quaryAll() throws JSONException, JsonProcessingException {
        Map listMap = new HashMap();
        ObjectMapper mapper = new ObjectMapper();
        List<SysResource> list = sysResourceService.findAll();
        List arrayList =new ArrayList();
        for ( SysResource sysResource : list){
            Object object  = sysResource ;
            if(sysResource.getSysResource() != null){
                //object = baseBeanDao.addAttributes(sysResource,"_parentId",sysResource.getSysResource().getId());
            }
            arrayList.add(object);
        }
        listMap.put("rows",arrayList);
        return mapper.writeValueAsString(listMap);
    }
    @PostMapping(value = "resources")
    public Map<String,Object> addResource(SysResource sysResource,String parentId){
        Map<String,Object>map=new HashedMap();
        SysResource parentSysResource=sysResourceService.findOne(Long.valueOf(parentId));
        sysResource.setSysResource(parentSysResource);
        try {
            sysResourceService.save(sysResource);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
        }
        return map;
    }
    @RequestMapping("removeResource")
    public Map<String,Object> removeResource(SysResource sysResource){
        Map<String,Object>map=new HashedMap();
        try {
            sysResource=sysResourceService.findOne(Long.valueOf(sysResource.getId()));
            sysResourceService.remove(sysResource);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
        }
        return map;
    }
}
